<?php
/***
 * MongoTool Service
 *
 *
 * @author    lanhongjie <lanhj@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */

namespace App\Services\MongoDBService;


use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MongoTool
{
    private static $conn;
    private static $collection_name;
    /**
     * MongoService constructor.
     * @param $conn
     */
    public function __construct()
    {
        self::$conn = self::getConn();
        self::$collection_name = self::collection();
    }

    /****
     * 获取MongoDB连接对象
     * @return mixed
     */
    public  function getConn(){
        if(empty(self::$conn)){
            self::$conn=DB::connection('mongodb');
        }
        return self::$conn;
    }


    /***
     * 存储图片到数据库中
     * @param $file_path
     * @return bool
     */
    public function gridFSstoreFile($file_path)
    {
        if(!file_exists($file_path)){
            return false;
        }
        $grid =self::getMongoGridFS();
        $file_id =$grid->storeFile($file_path);
        Log::info('file_id:'.$file_id);
        return $file_id;
    }
    /***
     *获取集合
     * @return mixed|string
     */
    private static function collection(){
        if(empty(self::$collection_name)){
            self::$collection_name='Image';
        }
        return self::$collection_name;
    }

    /***
     * 设置集合
     * @param $collection_name
     * @return bool
     */
    public  function setCollection($collection_name)
    {
        if(empty($collection_name)){
            return false;
        }
        self::$collection_name=$collection_name;
        return true;
    }
    public function generateMongoId()
    {
        $id=new \MongoId();
        return $id;
    }
    public static function getMongoGridFS()
    {
        $db=self::$conn;
        $grid=new \MongoGridFS($db);
        return $grid;
    }
}